package com.wanshi.servlet;

import com.wanshi.dao.UserDao;
import com.wanshi.entity.User;
import com.wanshi.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

@WebServlet("/ss/update")
public class UpdateServlet extends HttpServlet {

    private UserService userService = new UserService();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
            //1 获取用户表单提交的所有数据
            User user = new User();
            //前提 表单中表单元素的name属性值 和 对象的属性一致
        try {
            BeanUtils.copyProperties(user,request.getParameterMap());

            String[] hobbies = request.getParameterValues("hobby");


            //System.out.println("----------"+username);
            //1 单独处理爱好
            //篮球,足球,音乐
            StringBuffer buffer = new StringBuffer();
            for(String hobby:hobbies){
                buffer.append(hobby+",");
            }
            String hobby = buffer.substring(0,buffer.length()-1);
            user.setHobby(hobby);


            //2 操作数据库,修改用户
            userService.updateUser(user);

            response.sendRedirect(request.getContextPath()+"/ss/list");
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }



    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

